<!DOCTYPE html>
<?php

/* 
 * Copyright (c) 2012 Aalto University and University of Helsinki
 * MIT License
 * see LICENSE.txt for more information
 */

// global parameters
//$ENDPOINT = "http://localhost:8890/sparql"; // local Virtuoso endpoint
//$ENDPOINT = "http://localhost:3030/ds/query"; // local Fuseki endpoint
$ENDPOINT = "http://sparql.onki.fi/onki-light/sparql"; // ONKI Light Fuseki
//$ENDPOINT = "http://data.onki.fi/sparql/"; // data.onki.fi 4store endpoint
$graph = "http://www.yso.fi/onto/yso";

// set up EasyRdf & SPARQL endpoint
set_include_path(get_include_path() . PATH_SEPARATOR . '../lib/easyrdf/lib/');
require_once "EasyRdf.php";
$sparql = new EasyRdf_Sparql_Client($ENDPOINT);

// script parameters
$q = $_GET['q'];
// TODO should escape $q to prevent SPARQL injection ;)

if (!isset($q)) {
  echo "q parameter required";
  exit();
}


$query = <<<EOQ
SELECT * WHERE {
 GRAPH <$graph> {
 {
   ?s rdf:type skos:Concept .
   ?s skos:prefLabel ?label .
   FILTER (regex(?label, "^$q.*", "i") && langMatches(lang(?label), "FI"))
 }
 UNION
 {
   ?s rdf:type skos:Concept .
   ?s skos:prefLabel ?label .
   ?s skos:altLabel ?alabel .
   FILTER (regex(?alabel, "^$q.*", "i") && !regex(?label, "^$q.*", "i") && langMatches(lang(?alabel), "FI") && langMatches(lang(?label), "FI"))
 }
 }
 
} ORDER BY ?label
EOQ;


echo "<pre>" . htmlspecialchars($query) . "</pre>";
$result = $sparql->query($query);
//echo "got result:" . $result;
//echo $result->dump();
//echo "dumped";
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>prefix search</title>
</head>
<body>

<h1>Search: "<?php echo $q; ?>"</h1>
<ul>
<?php 
foreach($result as $row) {
  $uri = $row->s;
  $label = $row->label;
  if (isset($row->alabel)) {
    $altlabel = $row->alabel;
    echo "<li>$altlabel &rarr; <a href='concept.php?uri=$uri'>$label</a></li>\n";
  } else
    echo "<li><a href='concept.php?uri=$uri'>$label</a></li>\n";
}
?>
</ul>

</body>
</html>
